#!/usr/bin/env python

from iwin.spider.stock.yahoo import YahooPrice
from tzutil.ob import Ob
from tzutil.day import day_today
from iwin.db import PG
from math import log10, floor


def save_price(id, day, open, close, high, low, volume):
    volume = int(volume)
    for i in (open, close, high, low):
        if i == 'None':
            return
        try:
            i = float(i)
        except ValueError:
            return
        if i <= 0.0000001:
            return
    PG.insert(
        'stock.price',
        dict(
            code_id=id,
            open=open,
            close=close,
            high=high,
            low=low,
            day=day,
            volume=volume
        ),
        on_conflict=
        f"(code_id,day) DO UPDATE SET open=EXCLUDED.open,close=EXCLUDED.close,high=EXCLUDED.high,low=EXCLUDED.low,volume=EXCLUDED.volume"
    )


def _float(x):
    x = float(x)
    if x > 1:
        return round(x, 2)
    return round(x, 4 - int(floor(log10(abs(x)))))


#format=lambda x: (x or datetime(1900, 1, 1)).strftime("%Y%m%d")
def _price_li(id):
    r = []
    li = PG.select('stock.price', dict(code_id=id), order=("day", ))
    for i in li:
        r.append(
            [
                i.day,
                _float(i.open),
                _float(i.high),
                _float(i.low),
                _float(i.close), i.volume
            ]
        )
    return r


price_li = Ob()
yahoo_price = YahooPrice()


def price_li_hk(code_id, code):
    r = _price_li(code_id)
    if r:
        end_day = r[-1][0]
        if end_day >= day_today():
            return r
        begin = end_day * 86400
    else:
        begin = 0
    code = str(code).rjust(4, '0') + ".HK"

    li = yahoo_price(code, begin)

    for day, open, high, low, close, _close, volume in li:
        save_price(code_id, day, open, close, high, low, volume)
        r.append([day, open, high, low, close, volume])
    return r


price_li.HK = price_li_hk

# # Date,Open,High,Low,Close,Adj Close,Volume
# # 2007-02-01,23.566668,23.566668,23.566668,23.566668,17.874805,1800

# def main(country, code_func):
#     today = int((time.time() // 86400) * 86400)

#     for stock in PG.iter('stock.com', where={'country': country}):

#         print(stock.country, stock.market, stock.code, stock.name)

#         begin = price_last_date(
#             stock.id, lambda x: int(x.timestamp()) if x else 0
#         )
#         if begin == today:
#             continue

#         print(begin, today)

#         code = code_func(stock)
#         csv = yahoo_price(code, begin)
#         if not csv:
#             continue
#         try:
#             loads(csv)
#             continue
#         except:
#             pass

#         li = []

#         for i in csv_li(csv):
#             day, open, high, low, close, _close, volume = i
#             day = str2day(day)
#             save_price(stock.id, day, open, close, high, low, volume)

#main("HK", lambda i: i.code.rjust(4, '0') + ".HK")
# main("US", lambda i: i.code)
